package Exercise;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * Description：
 * Author: zhangc
 * Date：2017/8/29 16:15
 */
@tx
public class ProxyExcise implements Animal {


    @Override
    public void eat() {
        System.out.println("ProxyExercise");
    }

    @Override
    public int lala() {
        return 10000;
    }

    public static void main(String[] args) {
        Animal obj = new ProxyExcise();
        Animal proxyExcise = (Animal) Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//                if ("eat".equals(method.getName())) {
//                    System.out.println("===InvocationHandler===");
//                    return null;
//                }
                if (obj.getClass().isAnnotationPresent(tx.class))
                    System.out.println("Pressed by tx!!!");
                return method.invoke(obj, args);
            }
        });
        proxyExcise.eat();
        int lala = proxyExcise.lala();
        System.out.println(lala);
    }

}


interface Animal {
    void eat();

    int lala();
}

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface tx {

}
